package kr.hkit.summary_java.erp.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import kr.hkit.myframework.db.DbUtil;
import kr.hkit.summary_java.erp.dto.CodeTitle;

public class CodeTitleDao implements DaoInterface<CodeTitle> {
	private Connection connection;
	private PreparedStatement pstmt;
	
	public CodeTitleDao(Connection connection) {
		this.connection = connection;
	}
	@Override
	public void insertItem(CodeTitle item) throws SQLException {
		String sql = "insert into codetitle values(?, ?)";
		pstmt = connection.prepareStatement(sql);
		pstmt.setInt(1, item.getTitleNo());
		pstmt.setString(2, item.getTitleName());
		pstmt.executeUpdate();
		DbUtil.close(pstmt);
		DbUtil.close(connection);
	}

	@Override
	public void deleteItemByNo(CodeTitle item) throws SQLException {
		String sql = "delete codetitle where titleno = ?";
		pstmt = connection.prepareStatement(sql);
		pstmt.setInt(1, item.getTitleNo());
		pstmt.executeUpdate();
		DbUtil.close(pstmt);
		DbUtil.close(connection);
	}

	@Override
	public void updateItemByNo(CodeTitle item) throws SQLException {
		String sql = "update codetitle set titlename=? where titleno = ?";
		pstmt = connection.prepareStatement(sql);
		pstmt.setString(1, item.getTitleName());
		pstmt.setInt(2, item.getTitleNo());
		pstmt.executeUpdate();
		DbUtil.close(pstmt);
		DbUtil.close(connection);
	}

	@Override
	public ArrayList<CodeTitle> listItems() throws SQLException {
		ArrayList<CodeTitle> list = new ArrayList<>();
		String sql = "select * from codetitle";
		pstmt = connection.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		while(rs.next()){
			list.add(new CodeTitle(rs.getInt(1), rs.getString(2)));
		}
		DbUtil.close(rs);
		DbUtil.close(pstmt);
		return list;
	}

	@Override
	public CodeTitle searchItem(CodeTitle item) throws SQLException {
		CodeTitle codetitle = null;
		String sql = "select * from codetitle where titleno = ?";
		pstmt = connection.prepareStatement(sql);
		pstmt.setInt(1, item.getTitleNo());
		ResultSet rs = pstmt.executeQuery();
		
		if (rs.next()) {
			codetitle = new CodeTitle();
			codetitle.setTitleNo(rs.getInt(1));
			codetitle.setTitleName(rs.getString(2));
		}
		return codetitle;
	}
	
}
